package com.blue.spring.redis;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;

public class AtomicSequence
{
	private static Logger logger = LoggerFactory.getLogger(AtomicSequence.class);
	
	private RedisTemplate<String, Object> redisTemplate;
	private String key; // redis key
	private Integer length; // 序列长度
	private Integer type; // 类型，1普通，2日期
	private String prefix; // 前缀
	private String suffix; // 后缀
	
	public AtomicSequence()
	{
	}
	
	/**
	 * 重置计数器
	 */
	public void reset()
	{
		BoundValueOperations<String, Object> operations = redisTemplate.boundValueOps(key);
		operations.set(0);
	}
	
	/**
	 * 返回当前序列
	 */
	public String nextValue()
	{
		String pre = prefix == null ? "" : prefix;
		String suf = suffix == null ? "" : suffix;
		int len = length - pre.length() - suf.length();
		StringBuilder strVal = new StringBuilder(length).append(pre);

		BoundValueOperations<String, Object> operations = redisTemplate.boundValueOps(key);
		Long val = operations.increment(1L);
		logger.info("当前计数器[key={}]值：{}", key, val);
		if (type == 1)
		{
			strVal.append(StringUtils.leftPad(String.valueOf(val), len, '0'));
		}
		else
		{
			SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
			strVal.append(f.format(new Date()));
			strVal.append(StringUtils.leftPad(String.valueOf(val), len-8, '0'));
		}
		
		strVal.append(suf);
		return strVal.toString();
	}

	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate)
	{
		this.redisTemplate = redisTemplate;
	}

	public void setKey(String key)
	{
		this.key = key;
	}

	public void setLength(Integer length)
	{
		this.length = length;
	}

	public void setType(Integer type)
	{
		this.type = type;
	}

	public void setPrefix(String prefix)
	{
		this.prefix = prefix;
	}

	public void setSuffix(String suffix)
	{
		this.suffix = suffix;
	}
	
}
